﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CreatureSoft.Hoot.Data.Repositories;
using CreatureSoft.Hoot.Data.Infrastructure;
using CreatureSoft.Hoot.Domain.Security;
using System.Web.Security;

namespace CreatureSoft.Hoot.Service.Security
{
    public class UserService : IUserService
    {
        private readonly IUserRepository userRepository;
        private readonly IUnitOfWork unitOfWork;

        public UserService(IUserRepository userRepository, IUnitOfWork unitOfWork)
        {
            this.userRepository = userRepository;
            this.unitOfWork = unitOfWork;
        }

        public bool ValidateUser(string username, string password)
        {
            if (string.IsNullOrEmpty(password.Trim()) || string.IsNullOrEmpty(username.Trim()))
                return false;

            string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(password.Trim(), "md5");

            return this.userRepository.GetAll().Any(user => (user.UserName == username.Trim()) && (user.Password == hash));
                
        }

        public bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            if (!ValidateUser(username, oldPassword) || string.IsNullOrEmpty(newPassword.Trim()))
                return false;

            User user = userRepository.Get(m => m.UserName == username);
            string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(newPassword.Trim(), "md5");
            user.Password = hash;
            SaveUser();

            return true;
        }

        public void CreateUser(User user)
        {
            user.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(user.Password.Trim(), "md5");
            this.userRepository.Add(user);
            SaveUser();
        }


        public void SaveUser()
        {
            unitOfWork.Commit();
        }
    }
}
